<!-- eslint-disable indent -->
<template>
  <div class="relate-form2">
    <CpForm
      ref="searchForm"
      :model="searchModel"
      :items="searchFields"
      :rules="rules"
      :inline="inline"
      :class="collapse ? 'relate-form2-input-up' : 'relate-form2-input-down'"
      :label-width="labelWidth || '110px'"
      label-position="top"
      :style="{ height: styleHeights }"
    >
    </CpForm>
    <div
      v-if="operate && hasBtn"
      :class="[
        searchFields.length >= colNum || calClass2 > 20
          ? 'relate-form2-reviewbtn-2'
          : '',
        'relate-form2-reviewbtn'
      ]"
    >
      <c-button class="search" type="primary" @click="doSearch">
        查询
      </c-button>
      <c-button class="reset" @click="doReset">
        重置
      </c-button>
      <c-button
        v-if="
          drawerModel ||
            searchFields.length > colNum ||
            (calClass > 20 && calClass !== 24)
        "
        class="collapse"
        :icon="collapse ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
        @click="doCollapse"
      ></c-button>
    </div>
    <div
      v-if="!operate && hasBtn"
      :class="[
        searchFields.length >= colNum || calClass2 > 16
          ? 'relate-form2-reviewbtn-2'
          : '',
        'relate-form2-reviewbtn'
      ]"
    >
      <c-button class="search" type="primary" @click="doSearch">
        查询
      </c-button>
      <c-button class="reset" @click="doReset">
        重置
      </c-button>
      <c-button
        v-if="searchFields.length > colNum - 1"
        class="collapse"
        :icon="collapse ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
        @click="doCollapse"
      ></c-button>
    </div>
    <!-- <div v-if="collapse" class="relate-form2-mongolia"></div> -->
    <div class="relate-form2-content">
      <slot></slot>
    </div>
  </div>
</template>

<script>
import CpForm from '@/components/searchForm'
import { requestCommon } from '@/api/common'
export default {
  name: 'CateForm',
  components: { CpForm },
  props: {
    drawerModel: {
      type: Boolean,
      default: () => false
    },
    items: {
      type: Array,
      default: () => {
        return []
      }
    },
    searchModelAdd: {
      type: Object,
      default: () => {
        return {}
      }
    },
    inline: {
      type: Boolean,
      default: false
    },
    firstLineWarp: {
      type: Boolean,
      default: false
    },
    hasBtn: {
      type: Boolean,
      default: true
    },
    operate: {
      type: Boolean,
      default: true
    },
    colNum: {
      type: Number,
      default: 6
    },
    hasFuncBtn: {
      type: Boolean,
      default: true
    },
    labelWidth: {
      type: String,
      default: '90'
    },
    rules: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      suffix: '_map',
      list: {},
      searchModel: {
        ...this.searchModelAdd
      },
      searchFields: [],
      fieldMap: {},
      collapse: false,
      colNums: 0,
      colNum2: 0,
      styleHeights: ''
    }
  },
  computed: {
    calClass () {
      let num = 0
      const nums = this.searchFields
        .map((x) => x.anchor)
        .reduce((a, c) => a + c)
      if (this.searchFields.length < this.colNum || nums / this.colNum > 3) {
        num = nums
      }
      return num
    },
    calClass2 () {
      let num = 0
      const nums = this.searchFields
        .map((x) => x.anchor)
        .reduce((a, c) => a + c)
      if (this.searchFields.length < this.colNum) {
        num = nums
      }
      if (nums % this.colNum < this.colNum) {
        num = 0
      }
      if (nums % this.colNum === 0) {
        num = nums
      }
      return num
    }
  },
  watch: {
    items () {
      if (this.drawerModel) {
        this.init()
      }
    },
    collapse: {
      handler: function (v) {
        const box = document.getElementsByClassName('fields-box-item')
        const length = this.searchFields
          .map((x) => x.anchor)
          .reduce((a, c) => a + c)
        if (box.length > 5) {
          box[5].style.visibility = 'inherit'
        }
        const colNum = this.colNum
        if (v) {
          this.$nextTick(() => {
            const divHg = this.$refs.searchForm.$el.clientHeight
            this.styleHeights = divHg
            console.log('[ divHg ] >', divHg)
            const divHgw = document.getElementsByClassName(
              'relate-form2-reviewbtn'
            )[0]
            // console.log(length % colNum)
            // console.log(length / colNum)
            const finalNum = length / colNum
            console.log('[ finalNum ] >', finalNum)
            console.log('[ length ] >', length)
            if (!this.operate) {
              // 如果没有操作按钮
              divHgw.style.top = (this.styleHeights - 48) + 'px'
              if (length % 24 === 0) {
                const dom = document.getElementsByClassName('fields-box')[0]
                divHgw.style.top = (length / 24 * 74) + 'px'
                dom.style.marginBottom = 50 + 'px'
              }
              return false
            }
            if (length % 6 === 0) {
              divHgw.style.top = this.styleHeights + 'px'
            } else {
              divHgw.style.top = (this.styleHeights - 48) + 'px'
            }
          })
        } else {
          const divHgw = document.getElementsByClassName(
            'relate-form2-reviewbtn'
          )[0]
          if (!this.operate) {
            // 如果没有操作按钮
            if (box.length > 5) {
              box[5].style.visibility = 'hidden'
            }
            divHgw.style.top = 26 + 'px'
            return false
          }
          this.styleHeights = ''
          if (this.searchFields.length > this.colNum || length / colNum > 3) {
            divHgw.style.top = 74 + 'px'
          } else {
            divHgw.style.top = 26 + 'px'
          }
        }
      },
      deep: true
    }
  },
  created () {
    this.init()
  },
  mounted () {
    this.$nextTick(() => {
      if (!this.operate) { // 如果不带操作按钮
        const box = document.getElementsByClassName('fields-box-item')
        const divHgw = document.getElementsByClassName(
          'relate-form2-reviewbtn'
        )[0]
        if (box.length > 5) {
          box[5].style.visibility = 'hidden'
        }
        divHgw.style.top = 26 + 'px'
      }
    })
  },
  methods: {
    clear (value) {
      // console.log('resetValue',this.searchModel)
      if (value) {
        Object.assign(this.searchModel, value)
      } else {
        // this.searchModel = {...this.searchModelAdd}
        this.$refs['searchForm'].resetFields()
      }
    },
    clearItem (prop) {
      this.searchModel = {
        ...this.searchModel,
        [prop]: ''
      }
    },
    init () {
      this.items.forEach((item) => {
        this.fieldMap[item.prop] = item
        item.anchor = item.anchor || 4
        item.xStore &&
          Object.prototype.toString.call(item.xStore) === '[object Function]' &&
          (item.xStore = item.xStore.bind(this))
        //  Object.prototype.toString.call(item.xStore) === "[object Function]"判断当xStore类型为Function
        // 时，再去bind(this),而不至于在item.prop为其它类型时去使用xStore而页面报错
        // console.log('itemitemitem',item);
        const _build = item.build
        if (_build && _build.type === 'static' && _build.url) {
          this.require(_build, item).then(() => {
            if (_build.child) {
              const child = this.fieldMap[_build.child]
              this.$watch(`searchModel.${item.prop}`, (newV) => {
                this.searchModel[`${item.build.child}`] = ''
                if (newV === '') {
                  // reset
                  this.list[child.build.xStore] = []
                } else {
                  const params = {}
                  params[child.build.params] =
                    this[`${item.prop}${this.suffix}`][newV]
                  this.require(child.build, child, params)
                }
                this.$emit('modelChange', item.prop, newV)
              })
            }
          })
        } else {
          this.$watch(`searchModel.${item.prop}`, (newV) => {
            this.$emit('modelChange', item.prop, newV)
          })
        }
      })
      this.searchFields = this.items
    },
    require (build, filed, params) {
      return requestCommon({
        url: build.url,
        method: 'get',
        params
      }).then((res) => {
        if (res.success) {
          const mapKey = `${filed.prop}${this.suffix}`
          this[mapKey] = {}
          const finalData = res.data.map((item) => {
            this[mapKey][item[build.name]] = item[build.value]
            return {
              value: item[build.value],
              label: item[build.name]
            }
          })
          // console.log('finalDatafinalData', finalData)
          this.$set(this.list, build.xStore, finalData)
        }
      })
    },
    getData () {
      const res = {}
      for (const key in this.searchModel) {
        res[key] = this.searchModel[key]
      }
      return res
    },
    doSearch () {
      // if (this.collapse) {
      //   this.collapse = false
      // }
      this.$emit('searchFilter', this.getData())
    },
    doReset () {
      // if (this.collapse) {
      //   this.collapse = false
      // }
      for (const k in this.searchModel) {
        this.searchModel[k] = null
      }
      // this.$emit('searchFilter', this.getData())
      this.$emit('clear', this.getData())
    },
    doCollapse () {
      this.collapse = !this.collapse
      if (this.drawerModel) {
        this.$emit('collapse', this.collapse)
      }
    },
    validate () {
      return new Promise((resolve, reject) => {
        this.$refs['searchForm'].validate((valid) => {
          if (valid) {
            resolve(valid)
          } else {
            reject(valid)
          }
        })
      })
    },
    getFilterParams () {
      return this.getData()
    },
    resetFields () {
      //
      this.clear()
    }
  }
}
</script>
<style lang="scss" scoped>
$--widthsns: 24px;
$--paddings: 0 8px 0 24px;
.relate-form2 {
  height: 100%;
  position: relative;
  background: #fff;
  overflow-y: scroll;
  &-input-down,
  &-input-up {
    height: 74px;
    overflow: hidden;
    padding: $--paddings;
    position: relative;
    :deep(.fields-box) {
      display: flex;
      flex-wrap: wrap;
      margin: 0 !important;
      justify-content: flex-start; // 替代原先的space-between布局方式
      .fields-box-item {
        padding: 0 !important;
        padding-right: 16px !important;
        .el-form-item {
          .el-form-item__content {
            line-height: 32px;
            clear: both;
            .el-select,
            .el-radio-group {
              width: 100%;
            }
            .el-input__inner {
              height: 32px;
              line-height: 32px;
              // border-radius: 0;
            }
            .el-date-editor .el-range__icon,
            .el-date-editor .el-range__close-icon,
            .el-date-editor .el-range-separator {
              line-height: 25px;
              padding: 0 0 0 2px;
            }
            .el-date-editor .el-range__close-icon {
              width: 16px;
            }
            .el-date-editor--datetimerange.el-input,
            .el-date-editor--datetimerange.el-input__inner,
            .el-date-editor.el-input,
            .el-date-editor.el-input__inner {
              width: 100%;
            }
            .el-radio {
              margin-right: 25px;
            }
          }
        }
      }
    }
  }
  &-input-up {
    height: auto;
    width: 100%;
    z-index: 400;
    background: #fff;
  }
  &-reviewbtn {
    //搜索重制
    text-align: right;
    font-size: 12px;
    line-height: 32px;
    position: absolute;
    top: 26px;
    right: $--widthsns;
    z-index: 600;
    .search,
    .reset,
    .collapse {
      width: 60px;
      height: 32px;
      text-align: center;
      padding: 5px 16px;
      // border-radius: 0;
    }
    .search {
      background: #3786fd;
      color: #fff;
    }
    .collapse {
      width: 32px;
      padding: 5px 9px;
    }
    span {
      font-weight: 500;
    }
  }
  &-reviewbtn-2 {
    top: 74px;
  }
  &-mongolia {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.6);
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 100;
  }
  &-content {
    margin: 0px 24px;
    position: relative;
    // position: absolute;
    // top: 94px;
    // right: $--widthsns;
    // left: $--widthsns;
    // z-index: 1;
  }
}
</style>
